<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-button type="primary" class="functionBtn search-box" @click="addCateDialog">添加分类</el-button>
      <!-- 树型数据的表格 -->
      <tree-table :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" :show-index="true"
        border class="tree_table">
        <!-- 自定义内容：是否有效 -->
        <template slot='isok' slot-scope="scope">
          <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error" style="color:red" v-else></i>
        </template>
        <!-- 自定义内容：排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="danger" v-else>三级</el-tag>
        </template>
        <!-- 自定义内容:操作 -->
        <template slot="opt" slot-scope="scope">
          <!-- {{ scope.row }} -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateDialog(scope.row.cat_id)">
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCate(scope.row.cat_id)"></el-button>
        </template>
      </tree-table>
      <!-- 添加分类对话框 -->
      <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="30%" @close="resetAddCateForm">
        <el-form ref="addCateFormRef" :model="addCateForm" :rules="addCateFormRules" label-width="80px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <!-- 级联选择器 -->
            <el-cascader v-model=selectedKeys :options="parentsCateList" :props="cascaderProps"
              @change="parentsCateChange" clearable>
            </el-cascader>

          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="30%" @close="resetEditCateForm">
        <el-form ref="editCateFormRef" :model="cateData" :rules="addCateFormRules" label-width="80px">
          <el-form-item label="分类名称" prop="cat_name" clearable>
            <el-input v-model="cateData.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <!-- 级联选择器 -->
            <el-cascader v-model=selectedKeys :options="parentsCateList" :props="cascaderProps"
              @change="parentsCateChange">
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addEditCate">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 数据分页效果 -->
      <div class="block">
        <el-pagination :current-page="this.paramObj.pagenum" :page-sizes="[5, 10, 15]"
          :page-size="this.paramObj.pagesize" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper" :total="this.total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateData: {},
      paramObj: {
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      cateList: [],
      parentsCateList: [],
      columns: [
        // 第一列
        {
          label: '分类名称',
          prop: 'cat_name',
          key: 'cat_id'
        },
        // 第二列
        {
          label: '是否有效',
          // 将当前列定义为模板列
          type: 'template',
          // 模板名称为isok
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      // 添加分类对话框状态
      addDialogVisible: false,
      // 添加分类的表单数据
      addCateForm: {
        cat_name: '',
        cat_level: 0,
        // 父级分类的id
        cat_pid: 0,
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
      },
      // 指定级联选择器的配置对象
      cascaderProps: {
        // expand-trigger: 'hover',
        value: 'cat_id',
        // 指定你所看到的属性
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      // 选中的父级分类的id数组
      selectedKeys: [],
      // 编辑对话框状态
      editDialogVisible: false,

    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: this.paramObj })
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg("获取商品列表失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
      // console.log(this.cateList)
    },
    // 监听页面尺寸的改变
    handleSizeChange(newSize) {
      this.paramObj.pagesize = newSize;
      this.getCateList();
    },
    // 监听页码的改变
    handleCurrentChange(newPage) {
      this.paramObj.pagenum = newPage;
      this.getCateList();
    },
    // 添加分类对话框的展示
    addCateDialog() {
      // 获取父级分类数据
      this.getParentsCateList()
      this.addDialogVisible = true;
    },
    // 获取父级分类数据
    async getParentsCateList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg("获取商品父级列表失败");
      this.parentsCateList = res.data;
    },
    // 监听父级分类的改变
    parentsCateChange() {
      // console.log(this.selectedKeys)
      // 选中了父级分类
      if (this.selectedKeys.length > 0) {
        // 更改所属直接父级的id
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
        // 更改所属直接父级的等级，等级0，1，2，最高等级是0
        this.addCateForm.cat_level = this.selectedKeys.length;
        // 防止不断循环
        return;
      }
      else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    // 添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('categories', this.addCateForm);
          // console.log(res)
          if (res.meta.status !== 201) return this.$msg.error("添加分类失败");
          this.$msg.success("添加分类成功");
          // 刷新页面
          this.getCateList();
        }
      })
      this.addDialogVisible = false;
    },
    // 重置添加分类表单
    resetAddCateForm() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    // 根据id查询分类，编辑对话框的展示
    async editCateDialog(id) {
      this.editDialogVisible = true;
      this.getParentsCateList()
      const { data: res } = await this.$http.get(`categories/${id}`);
      console.log(res);
      if (res.meta.status !== 200) return this.$msg.error("查询分类失败");
      this.cateData = res.data;

    },
    // 编辑对话框的重置
    resetEditCateForm() {
      this.$refs.editCateFormRef.resetFields();
    },
    // 编辑对话框的提交
    addEditCate() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`categories/${this.cateData.cat_id}`, {
            cat_name: this.cateData.cat_name
          });
          // console.log(cat_name)
          console.log(res)
          if (res.meta.status !== 200) return this.$msg.error("编辑的用户添加失败");
          // 添加用户成功
          this.$msg.success(res.meta.msg);
          // 重新渲染
          this.getCateList();
          // 关闭编辑用户对话框
          this.editDialogVisible = false;
        }
      })
    },
    // 删除分类
    removeCate(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`categories/${id}`).then((res) => {
          // console.log(res)
          if (res.status !== 200) return this.$msg.error("删除分类失败");
          this.$msg({
            type: 'success',
            message: '删除分类成功!'
          });
          // 重新渲染
          this.getCateList();
        });
      }).catch(() => {
        this.$msg({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  created() {
    this.getCateList();
  }
}


</script>

<style lang="less" scoped>
.tree_table {
  margin: 15px 0;
}
</style>